package com.handu.luna.core.domain.promotion;

import com.handu.luna.core.domain.BasePersistentDomain;
import com.handu.luna.core.domain.user.User;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import javax.persistence.Entity;
import javax.persistence.Transient;

import java.util.List;

/**
 * Created by wangzailiang on 2014/6/27.
 */
@Entity
public class PostCard extends BasePersistentDomain<PostCardRepository> {

    private String code;
    private Long postCardPromotionId;
    private Long userId;
    private Long usedNum = 0L;
    @Transient private PostCardPromotion postCardPromotion;
    @Transient private User user;

    /**
    * 通过包邮卡类型ID查询所有包邮卡(分页)
    * @param postCardPromotionId
    * @param pageable
    * @return
    */
    public Page<PostCard> findAllByPostCardPromotionId(Long postCardPromotionId,Pageable pageable) {
        Page<PostCard> page = context.getPostCardRepository().findAllByPostCardPromotionId(postCardPromotionId, pageable);
        List<PostCard> list = page.getContent();
        for(PostCard postCard : list) {
            postCard.init();
        }
        return page;
    }

    /**
     * 通过包邮卡类型ID查询所有包邮卡
     * @param postCardPromotionId
     * @return
     */
    public List<PostCard> findAllByPostCardPromotionId(Long postCardPromotionId) {
        List<PostCard> list = context.getPostCardRepository().findAllByPostCardPromotionId(postCardPromotionId);
        for(PostCard postCard : list) {
            postCard.init();
        }
        return list;
    }

    public PostCard save(PostCard postCard) {
        postCard.generateCode();
        context.getPostCardRepository().save(postCard);
        return postCard;
    }

    public void delete(Long id,Long postCardPromotionId) {
        PostCard postCard = context.getPostCardRepository().findOne(id);
        new PostCardPromotion().updateGrantNum(-1L,postCardPromotionId);
        if(null != postCard.getUserId()  && 0 != postCard.getUserId()) {
            new PostCardPromotion().updateUsedNum(-1L,postCardPromotionId);
        }

        context.getPostCardRepository().delete(id);
    }

    /**
     * 根据类型ID 和发放数量 发放
     * @param postCardPromotionId
     * @param grantNum
     */
    public void save(Long postCardPromotionId, Long grantNum) {

        for(int i=0; i<grantNum; i++) {
            PostCard postCard = new PostCard();
            postCard.setPostCardPromotionId(postCardPromotionId);
            this.save(postCard);
        }

        new PostCardPromotion().updateNum(postCardPromotionId,grantNum);
    }

    /**
     * 生成包邮卡号
     */
    public void generateCode() {
        StringBuilder code = new StringBuilder(String.valueOf(postCardPromotionId));
        code.append(System.nanoTime());
        setCode(code.toString());
    }

    public void init() {
        setPostCardPromotion(context.getPostCardPromotionRepository().findOne(getPostCardPromotionId()));
        if(userId != null) {
            setUser(context.getUserRepository().findOne(getUserId()));
        }
    }




    public PostCard(){}

    public PostCard(String code, Long postCardPromotionId, Long userId, Long usedNum) {
        this.code = code;
        this.postCardPromotionId = postCardPromotionId;
        this.userId = userId;
        this.usedNum = usedNum;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Long getPostCardPromotionId() {
        return postCardPromotionId;
    }

    public void setPostCardPromotionId(Long postCardPromotionId) {
        this.postCardPromotionId = postCardPromotionId;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public Long getUsedNum() {
        return usedNum;
    }

    public void setUsedNum(Long usedNum) {
        this.usedNum = usedNum;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public PostCardPromotion getPostCardPromotion() {
        return postCardPromotion;
    }

    public void setPostCardPromotion(PostCardPromotion postCardPromotion) {
        this.postCardPromotion = postCardPromotion;
    }


    public HSSFWorkbook getExcelModel(Long postCardPromotionId) {

        @SuppressWarnings("unused")
		PostCardPromotion postCardPromotion = context.getPostCardPromotionRepository().findOne(postCardPromotionId);
        List<PostCard> postCardList = new PostCard().findAllByPostCardPromotionId(postCardPromotionId);

        HSSFWorkbook wb = new HSSFWorkbook();
        int sheetCount = postCardList.size()/60000 + 1;
        int beginIndex = 0;
        int endIndex = sheetCount > 1 ? 60000 : postCardList.size();

        for (int sheetNum = 1; sheetNum <= sheetCount; sheetNum++) {

            HSSFSheet sheet = wb.createSheet("包邮卡"+(sheetCount > 1 ? sheetNum :""));
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("包邮卡序列号");
            headerRow.createCell(1).setCellValue("包邮卡类型");
            headerRow.createCell(2).setCellValue("使用时限");
            headerRow.createCell(3).setCellValue("使用次限");

            for(int i=beginIndex,j=0; i<endIndex; i++,j++) {
                PostCard postCard = postCardList.get(i);

                Row row = sheet.createRow(j+1);
                row.createCell(0).setCellValue(postCard.getCode());
                row.createCell(1).setCellValue(postCard.getPostCardPromotion().getName());
                row.createCell(2).setCellValue(postCard.getPostCardPromotion().getMonthLimitCount().toString());
                row.createCell(3).setCellValue(postCard.getPostCardPromotion().getTimesLimitCount().toString());
            }

            beginIndex = 60000 * sheetNum;
            endIndex = sheetCount > (sheetNum+1) ? 60000*(sheetNum + 1) : postCardList.size();
        }

        return wb;
    }
}
